package com.crane.oss.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.SysException;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.common.framework.utils.DateUtil;
import com.crane.oss.enums.SectionEnum;
import com.crane.oss.school.bean.request.QueryClassCountReq;
import com.crane.oss.school.bean.request.QueryClassesInfoReq;
import com.crane.oss.school.bean.request.QueryCourseSetReq;
import com.crane.oss.school.bean.request.courseset.AddCourseSetReq;
import com.crane.oss.school.bean.request.courseset.UpdateCourseSetReq;
import com.crane.oss.school.bean.resp.ClassesInfoResp;
import com.crane.oss.school.bean.resp.CourseSetResp;
import com.crane.oss.school.dao.CourseSetDao;
import com.crane.oss.school.dao.TeacherCycleDao;
import com.crane.oss.school.dao.TestCycleDao;
import com.crane.oss.school.model.Area;
import com.crane.oss.school.model.CourseSet;
import com.crane.oss.school.model.TeacherCycle;
import com.crane.oss.school.model.TestCycle;
import com.crane.oss.school.service.ClassesInfoService;
import com.crane.oss.school.service.CourseSetService;
import com.crane.oss.school.service.TestCycleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhenxing.pi
 * @email ccsu123456@qq.com
 * @date 2022年03月26日 14时24分54秒
 */
@Service
@Slf4j
public class CourseSetServiceImpl implements CourseSetService {

    @Resource
    protected CourseSetDao courseSetDao;

    @Resource
    protected TeacherCycleDao teacherCycleDao;

    @Resource
    ClassesInfoService classesInfoService;

    @Override
    public CourseSetResp queryCourseSet(Long id) {
        log.info("CourseSetBOImpl queryCourseSet id={}", id);
        CourseSet courseSet = courseSetDao.selectById(id);
        if (null == courseSet) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "courseSet");
        }
        CourseSetResp courseSetResp = new CourseSetResp();
        BeanUtil.copyProperties(courseSet, courseSetResp);
        return courseSetResp;
    }

    @Override
    public IPage<CourseSetResp> queryList(QueryCourseSetReq queryRequest) {
        log.info("CourseSetBOImpl queryList queryRequest={}", queryRequest);
        IPage<CourseSetResp> result = new Page<>();
        result.setCurrent(queryRequest.getPageNo());
        result.setPages(queryRequest.getPageSize());

        LambdaQueryWrapper<CourseSet> queryCourseSetWrapper = new LambdaQueryWrapper<>();
        queryCourseSetWrapper.eq(ObjectUtils.isNotNull(queryRequest.getPartyId()), CourseSet::getPartyId, queryRequest.getPartyId());
        queryCourseSetWrapper.orderByAsc(CourseSet ::getGrade);
        IPage<CourseSet> page = courseSetDao.selectPage(new Page<>(queryRequest.getPageNo(), queryRequest.getPageSize()), queryCourseSetWrapper);
        return page.convert(u -> {
            CourseSetResp v = new CourseSetResp();
            if(u.getGrade()<7){
                v.setSchoolPeriod(SectionEnum.PRIMARY_SCHOOL.getRemark());
            }else if(u.getGrade() >= 7 && u.getGrade() < 10){
                v.setSchoolPeriod(SectionEnum.JUNIOR_HIGH_SCHOOL.getRemark());
            }else if(u.getGrade() >= 10) {
                v.setSchoolPeriod(SectionEnum.HIGH_SCHOOL.getRemark());
            }else{
                throw new SysException("年级错误");
            }
            BeanUtils.copyProperties(u, v);
            return v;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(AddCourseSetReq addRequest) {
        log.info("CourseSetBOImpl save request={}", addRequest);

        LambdaQueryWrapper<CourseSet> queryCourseSetWrapper = new LambdaQueryWrapper<>();
        queryCourseSetWrapper.eq(CourseSet ::getPartyId,addRequest.getPartyId());
        queryCourseSetWrapper.eq(CourseSet ::getGrade,addRequest.getGrade());

        int i = 0;
        CourseSet dbCourseSet=courseSetDao.selectOne(queryCourseSetWrapper);
        if(null !=dbCourseSet){
            dbCourseSet.setCourseNumber(addRequest.getCourseNumber());
            i = courseSetDao.updateById(dbCourseSet);
        }else{
            CourseSet courseSet = new CourseSet();
            BeanUtil.copyProperties(addRequest, courseSet);
            if(addRequest.getGrade()<7){
                courseSet.setSchoolPeriod(SectionEnum.PRIMARY_SCHOOL.getType());
            }else if(addRequest.getGrade() >= 7 && addRequest.getGrade() < 10){
                courseSet.setSchoolPeriod(SectionEnum.JUNIOR_HIGH_SCHOOL.getType());
            }else if(addRequest.getGrade() >= 10) {
                courseSet.setSchoolPeriod(SectionEnum.HIGH_SCHOOL.getType());
            }else{
                throw new SysException("年级错误");
            }

            courseSet.setCreateTime(new Date());
            try {
                i = courseSetDao.insert(courseSet);
            } catch (Exception e) {
                log.info("CourseSetBOImpl add e={}", e);
                throw new SysException();
            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(UpdateCourseSetReq updateRequest) {
        log.info("CourseSetServiceImpl update request={}", updateRequest);
        CourseSet db = courseSetDao.selectById(updateRequest.getId());
        if (null == db) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "courseSet");
        }
        if(!db.getPartyId().equals(updateRequest.getPartyId())){
            throw new AppException(BasicErrorCode.NO_DATA_RIGHT);
        }
        LambdaQueryWrapper<CourseSet> queryCourseSetWrapper = new LambdaQueryWrapper<>();
        queryCourseSetWrapper.eq(CourseSet ::getPartyId,updateRequest.getPartyId());
        queryCourseSetWrapper.eq(CourseSet ::getGrade,updateRequest.getGrade());
        CourseSet dbCourseSet=courseSetDao.selectOne(queryCourseSetWrapper);
        if(null != dbCourseSet && !db.getId().equals(updateRequest.getId())){
            throw new AppException(BasicErrorCode.ENTITY_IS_EXISTS, "年级设置");
        }

        CourseSet courseSet = new CourseSet();
        BeanUtil.copyProperties(updateRequest, courseSet);
        courseSet.setUpdateTime(new Date());
        int i = 0;
        try {
            i = courseSetDao.updateById(courseSet);
        } catch (Exception e) {
            log.info("CourseSetServiceImpl add e={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        log.info("CourseSetServiceImpl delete id={}", id);
        return courseSetDao.deleteById(id);
    }

    @Override
    public int queryClassArangementCount(QueryClassCountReq request) {
        int count=0;
        QueryClassesInfoReq queryClassesInfoReq=new QueryClassesInfoReq();
        queryClassesInfoReq.setPageSize(10000);
        queryClassesInfoReq.setPartyId(request.getPartyId());
        IPage<ClassesInfoResp> page = classesInfoService.queryList(queryClassesInfoReq);
        List<Integer> gradeList=page.getRecords().stream().map(ClassesInfoResp ::getGrade).distinct().collect(Collectors.toList());

        LambdaQueryWrapper<CourseSet> queryCourseSetWrapper = new LambdaQueryWrapper<>();
        queryCourseSetWrapper.in(CourseSet ::getGrade,gradeList);
        List<CourseSet> courseSetRespList=courseSetDao.selectList(queryCourseSetWrapper);
        if(!courseSetRespList.isEmpty()){
            int week =0;
            if(request.getFlag() ==0){
                week=DateUtil.daysBetween(request.getEndTime(),request.getBeginTime())/7;
            }else{
                TeacherCycle teacherCycle=teacherCycleDao.selectById(request.getCycleId());
                if(null !=teacherCycle){
                    week=DateUtil.daysBetween(teacherCycle.getCycleEndTime(),teacherCycle.getCycleStartTime())/7;
                }
            }
            for(CourseSet courseSet:courseSetRespList){
                count=count+courseSet.getCourseNumber()*week;
            }
        }
        return count;
    }


    public static void main(String[] args) {

    }
}
